package org.squabble.service;

import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.squabble.dao.SystemPropertyDAO;
import org.squabble.domain.SystemProperty;
import org.squabble.web.admin.SystemSettingsCommand;
import org.squabble.web.admin.SystemDisplayCommand;
import org.squabble.web.admin.SystemEmailCommand;

@Service
public class SystemService {

	@Autowired
	SystemPropertyDAO systemPropertyDAO;

	public SystemProperty getSystemProperty(String name) {
		return systemPropertyDAO.getSystemProperty(name);
	}

	public Map<String, SystemProperty> getSystemPropertyMap() {
		return systemPropertyDAO.getSystemPropertyMap();
	}

	@Transactional(propagation = Propagation.REQUIRED)
	public void updateSystemProperties(SystemSettingsCommand sc) {
		updateProperty("systemCacheTime", sc.getSystemCacheTime());
		updateProperty("systemEnabled", sc.getSystemEnabled());
		updateProperty("systemMaintenanceMessage", sc
				.getSystemMaintenanceMessage());
		updateProperty("systemSiteName", sc.getSystemSiteName());
		updateProperty("systemSiteURL", sc.getSystemSiteURL());
		updateProperty("userRegistrationAllow", sc.getUserRegistrationAllow());
		updateProperty("userRegistrationApproval", sc
				.getUserRegistrationApproval());

	}

	@Transactional(propagation = Propagation.REQUIRED)
	public void updateEmailProperties(SystemEmailCommand sc) {
		updateProperty("emailAddress", sc.getEmailAddress());
		if (StringUtils.isNotBlank(sc.getEmailPassword())) {
			updateProperty("emailPassword", sc.getEmailPassword());
		}
		updateProperty("emailSMTPPort", sc.getEmailSMTPPort());
		updateProperty("emailSMTPServer", sc.getEmailSMTPServer());
		updateProperty("emailUser", sc.getEmailUser());
		updateProperty("emailUseSSL", sc.getEmailUseSSL());
		updateProperty("emailUseTLS", sc.getEmailUseTLS());

	}

	@Transactional(propagation = Propagation.REQUIRED)
	public void updateDisplayProperties(SystemDisplayCommand sc) {
		updateProperty("indexDisplayCount", sc.getIndexDisplayCount());
	}

	@Transactional(propagation = Propagation.REQUIRED)
	protected void updateProperty(String name, Object value) {
		SystemProperty property = systemPropertyDAO.getSystemProperty(name);
		property.setValue(value);
	}

}
